package com.code.pattern.prototype;

import java.util.ArrayList;
import java.util.List;

/**
 * 原型模式测试
 * @author lyf
 * @date 2021-03-18 下午2:08
 */
public class RealizeTypeTest {
    public static void main(String[] args) throws Exception {

        // test();

        // for循环批量生产对象测试
        // forBatchTest();

        // 应用类型测试
        // referenceTest();

        // 深度克隆-应用类型测试
        deepCloneReferenceTest();
    }

    private static void deepCloneReferenceTest() {
        RealizeType obj1 = new RealizeType("张三", 12);
        List<String> hobbies = new ArrayList<String>();
        hobbies.add("复制");
        hobbies.add("拷贝");
        obj1.setHobbies(hobbies);
        System.out.println("obj1: " + obj1);

        RealizeType obj2 = obj1.deepClone();
        obj2.getHobbies().add("不留痕迹");

        System.out.println("obj1: " + obj1);
        System.out.println("obj2: " + obj2);
    }

    private static void referenceTest() throws Exception {

        RealizeType obj1 = new RealizeType("张三", 12);
        List<String> hobbies = new ArrayList<String>();
        hobbies.add("复制");
        hobbies.add("拷贝");
        obj1.setHobbies(hobbies);
        System.out.println("obj1: " + obj1);

        RealizeType obj2 = obj1.clone();
        obj2.getHobbies().add("不留痕迹");

        System.out.println("obj1: " + obj1);
        System.out.println("obj2: " + obj2);
    }

    /**
     * 浅克隆 - 单个对象测试
     * @throws Exception
     */
    public static void test() throws Exception {
        RealizeType obj1 = new RealizeType("张三", 12);
        RealizeType obj2 = obj1.clone();
        System.out.println("obj1: " + obj1);
        System.out.println("obj2: " + obj2);
        System.out.println("obj1==obj2? " + (obj1 == obj2));

        obj2.setName("李四");
        System.out.println("obj1: " + obj1);
        System.out.println("obj2: " + obj2);
    }

    /**
     * 浅克隆 - for循环批量生成对象的时候可以在for循环外层先创建一个原型对象，在再for循环内部调用clone方法
     * @throws Exception
     */
    public static void forBatchTest() throws Exception {
        RealizeType obj1 = new RealizeType("张三", 12);

        for (int i = 0; i < 3; i++) {
            RealizeType obj2 = obj1.clone();
            System.out.println("obj1: " + obj1);
            System.out.println("obj2: " + obj2);
            System.out.println("obj1==obj2? " + (obj1 == obj2));

            obj2.setName("李四-" + i);
            System.out.println("obj1: " + obj1);
            System.out.println("obj2: " + obj2);

            System.out.println("=============第一批对象生成完成============");
        }
    }
}
